package com.jisf.driver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jisf.driver.entity.po.User;
import com.jisf.driver.response.Result;
import com.jisf.driver.service.LoginService;
import com.jisf.driver.utils.JwtUtil;
import com.jisf.driver.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Classname LoginServiceImpl
 * @Description TODO
 * @Date 2022/4/7 12:44
 * @Created by jisf：【429627912@qq.com】
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public Result<?> login(User user) {
        //AuthenticationManager进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出相应提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登陆失败");
        }
        //如果认证通过，使用userid生成一个jwt
        UserDetailsImpl userDetailsImpl = (UserDetailsImpl) authenticate.getPrincipal();
        User userDetails = userDetailsImpl.getUser();
        Integer id = userDetails.getId();
        String jwtToken = JwtUtil.createJwt(id);
        Map<String, String> map = new HashMap<>();
        map.put("token",jwtToken);

        String str_user = JSONObject.toJSONString(userDetails);
        map.put("user", str_user);

        //把完整用户信息存入redis，userid作为key
        redisUtil.setCacheObject("userId:" + id, userDetailsImpl);
        return Result.ok(200, "登录成功", map);
    }

    /**
     * 退出登录
     * @return
     */
    @Override
    public Result<?> logout() {
        //获取SecurityContextHolder中的用户信息
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        Integer userId = userDetails.getUser().getId();

        //删除redis中的值
        redisUtil.deleteObject("userId:" + userId);
        return Result.ok(200, "退出成功");
    }
}
